const express = require("express");
const { ApolloServer, gql } = require("apollo-server-express");
// const { ApolloServer, gql } = require("apollo-server");

const app = express();

const libraries = [
  {
    branch: "downtown",
  },
  {
    branch: "riverside",
  },
];

const books = [
  {
    title: "The Awakening",
    author: "Kate Chopin",
    branch: "riverside",
  },
  {
    title: "City of Glass",
    author: "Paul Auster",
    branch: "downtown",
  },
];

const typeDefs = gql`
  type Library {
    branch: String!
    books: [Book!]
  }

  type Book {
    title: String!
    author: Author!
  }

  type Author {
    name: String!
  }

  type Query {
    libraries: [Library]
  }
`;

const resolvers = {
  // 所有的 Query 都走这里
  Query: {
    libraries(parent, args, context) {
      return libraries;
    },
  },
  Library: {
    // 这些解析器按上述顺序执行，并将其返回值通过父参数传递给链中的下一个解析器。
    books(parent, args, context) {
      return books.filter((book) => book.branch === parent.branch);
    },
  },
  Book: {
    author(parent) {
      return {
        name: parent.author,
      };
    },
  },
};

const server = new ApolloServer({ typeDefs, resolvers });
server.applyMiddleware({ app });

app.use((req, res) => {
  res.status(200);
  res.send("Hello!");
  res.end();
});

app.listen(4000, () => {
  console.log(
    `Server is running on http://localhost:4000${server.graphqlPath}`
  );
});
